
package com.yitongmao.common;

import android.content.Context;
import android.os.Environment;

import com.yitongmao.common.reminder.ReaderApplication;
import com.yitongmao.util.Loger;
import com.yitongmao.util.StringUtils;
import com.yitongmao.yitmfruit.R;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;



/**
 * 类说明： 文件读写 如果往手机中写文件，文件保存在 /data/data/com.founder.newaircloud/files 目录下 如果是SD卡，则自建目录
 * @author Liucd
 * @version 1.0
 * @date Sep 29, 2010 6:50:25 AM
 */
public class FileUtils {

    /**
     * 下载时，至少剩余的sd卡空间大小 8M
     */
    private static final long MIN_LEFT_STORE = 1024 * 1024 * 8;

    /**
     * 缓冲区大小
     */
    public static final int BUFF_SIZE = 1024 * 4;

    private final static String TAG = "FileUtils";
    // 缓存存储到手机上
    public static int STORE_PLACE_PHONE = 1;

    // 缓存存储到SD卡上
    public static int STORE_PLACE_SDCARD = 2;

    // 文件的大小
    public static long size = 0;
    /**
     * @author cyliu
     */
    private static final String SDCardRoot = Environment
            .getExternalStorageDirectory().getAbsolutePath();
    public static final String APP_DIR = SDCardRoot + File.separator
            + ReaderApplication.getInstace().getResources().getString(R.string.end_living_list);
    public static final String DIR_DOWNLOAD = APP_DIR + File.separator
            + "downloads";

    public static final String ImagePictures = SDCardRoot
            + File.separator
            + "Pictures"
            + File.separator
            + ReaderApplication.getInstace().getResources().getString(R.string.share_completed);

//    absoluteFolder = context.getFilesDir() + File.separator
//    + folderName + File.separator;

    public static final String ImageCacheSD = SDCardRoot
            + File.separator
            + ReaderApplication.getInstace().getResources().getString(R.string.abc_action_bar_home_subtitle_description_format)
            + File.separator + "imageCache";

    static {
        File dirDownload = new File(DIR_DOWNLOAD);
        if (!dirDownload.exists()) {
            dirDownload.mkdirs();
        }
        dirDownload = null;
    }

    public static final String IMAGE_LOADER_CACHE_PATH = "/FounderReader/Images/";

    public static String getFilesDirPhone(Context context) {
        return context.getFilesDir() + File.separator
                + ReaderApplication.getInstace().getResources().getString(R.string.abc_font_family_menu_material);
    }

    /**
     * 获取当前文件存储位置
     *
     * @return
     */
    public static int getStorePlace() {
        return STORE_PLACE_PHONE;
        // return STORE_PLACE_SDCARD;
    }

    /**
     * 判断文件是否存在
     *
     * @param context
     * @param folderName
     * @param fileName
     * @param storePlace
     * @return
     */
    public static boolean isFileExist(Context context, String folderName,
                                      String fileName, int storePlace) {
        File file = getFile(context, folderName, fileName, storePlace);
        return file != null && file.exists();
    }

    /**
     * 删除文件
     *
     * @param context
     * @param folderName
     * @param fileName
     * @param storePlace
     * @return
     */
    public static boolean delete(Context context, String folderName,
                                 String fileName, int storePlace) {
        boolean ret = false;
        if (isFileExist(context, folderName, fileName,
                FileUtils.STORE_PLACE_PHONE) || isFileExist(context, folderName, fileName,
                FileUtils.STORE_PLACE_SDCARD)) {
            File file = getFile(context, folderName, fileName, storePlace);
            Loger.i(TAG, "delete=======delete-file======="
                    + file.getPath());
            ret = file.delete();
        }
        return ret;
    }

    /**
     * 根据文件目录和文件名获取File对象
     *
     * @param context
     * @param folderName
     * @param storePlace
     * @return
     */
    public static File getFile(Context context, String folderName,
                               int storePlace) {
        File file = null;
        if (STORE_PLACE_PHONE == storePlace) {
            String absolutePath = context.getFilesDir() + File.separator
                    + folderName;
            file = new File(absolutePath);
        } else {
            String absolutePath = Environment.getExternalStorageDirectory()
                    + File.separator + folderName;
            file = new File(absolutePath);
        }

        return file;
    }

    //写入
    public static File write2SDFromInput(String fileName, InputStream inputStream) {
        FileOutputStream outputStream = null;
        File file = null;

        try {
            if (FileUtils.ExistSDCard()) {
                file = new File(DIR_DOWNLOAD + "/" + fileName);
            } else {
                file = new File(getFilesDirPhone(ReaderApplication.getInstace()) + "/" + fileName);
            }
            File fileDir = file.getParentFile();
            if (fileDir != null && !fileDir.exists()) {
                fileDir.mkdirs();
            }

            if (fileDir.exists()) {
                // 删除文件或目录
                FileUtils.deleteFiles(fileDir);
                //fileDir.delete();
            }

            if (!file.exists()) {
                file.createNewFile();
            }

            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int readLength;
            while ((readLength = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, readLength);
            }

            outputStream.flush();
        } catch (Exception var15) {
            var15.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                    outputStream = null;
                } catch (IOException var14) {
                    var14.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return file;
    }    //写入

    public static File write2SDFromInput(String fileFoder, String fileName, InputStream inputStream) {
        FileOutputStream outputStream = null;
        File file = null;

        try {

            file = new File(fileFoder + "/" + fileName);
            File fileDir = file.getParentFile();
            if (fileDir != null && !fileDir.exists()) {
                fileDir.mkdirs();
            }

            if (fileDir.exists()) {
                // 删除文件或目录
                FileUtils.deleteFiles(fileDir);
                //fileDir.delete();
            }

            if (!file.exists()) {
                file.createNewFile();
            }

            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int readLength;
            while ((readLength = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, readLength);
            }

            outputStream.flush();
        } catch (Exception var15) {
            var15.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                    outputStream = null;
                } catch (IOException var14) {
                    var14.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return file;
    }

    public static File write2SDFromInputNoDelete(String fileFoder, String fileName, InputStream inputStream) {
        FileOutputStream outputStream = null;
        File file = null;

        try {

            file = new File(fileFoder + "/" + fileName);
            File fileDir = file.getParentFile();
            if (fileDir != null && !fileDir.exists()) {
                fileDir.mkdirs();
            }

            if (!file.exists()) {
                file.createNewFile();
            }

            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int readLength;
            while ((readLength = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, readLength);
            }

            outputStream.flush();
        } catch (Exception var15) {
            var15.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                    outputStream = null;
                } catch (IOException var14) {
                    var14.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return file;
    }


    //写入
    public static File writeImages2SDFromInput(String fileName, InputStream inputStream) {
        FileOutputStream outputStream = null;
        File file = null;

        try {

            file = new File(ImagePictures + "/" + fileName);
            File fileDir = file.getParentFile();
            if (fileDir != null && !fileDir.exists()) {
                fileDir.mkdirs();
            }

            if (!file.exists()) {
                file.createNewFile();
            }

            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int readLength;
            while ((readLength = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, readLength);
            }

            outputStream.flush();
        } catch (Exception var15) {
            var15.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                    outputStream = null;
                } catch (IOException var14) {
                    var14.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return file;
    }

    public static final int CONTENT = 0;

    public static final int WEATHER = 1;

    /**
     * 根据文件目录和文件名获取File对象
     *
     * @param context
     * @param folderName
     * @param fileName
     * @param storePlace
     * @return
     */
    public synchronized static File getFile(Context context, String folderName,
                                            String fileName, int storePlace) {
        File file = null;
        if (STORE_PLACE_PHONE == storePlace) {
            String absolutePath = ReaderApplication.getInstace().getFilesDir() + File.separator
                    + folderName;
            Loger.i(TAG, "配置信息存储在手机里的路径====" + absolutePath);
            file = new File(absolutePath, fileName);
        } else {
            String absolutePath = Environment.getExternalStorageDirectory()
                    + File.separator + folderName;
            Loger.i(TAG, "配置信息存储在SD卡里的路径====" + absolutePath);
            file = new File(absolutePath, fileName);
        }

        return file;
    }

    /**
     * 向手机或者SD卡写文件
     *
     * @param context
     * @param folderName
     * @param fileName
     * @param buffer
     * @param storePlace
     * @return
     */
    public synchronized static boolean writeFile(Context context,
                                                 String folderName, String fileName, byte[] buffer, int storePlace) {
        boolean writeSucc = false;
        String absoluteFolder = "";

        if (STORE_PLACE_PHONE == storePlace) {
            absoluteFolder = context.getFilesDir() + File.separator
                    + folderName + File.separator;
        } else {
            boolean sdCardExist = Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED);

            if (sdCardExist) {
                absoluteFolder = Environment.getExternalStorageDirectory()
                        + File.separator + folderName + File.separator;
            } else {
                absoluteFolder = "";
            }
        }
        Loger.i("AAA", "AAA--getui--absoluteFolder:" + absoluteFolder);
        if (!StringUtils.isBlank(absoluteFolder)) {
            File fileDir = new File(absoluteFolder);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            File file = new File(absoluteFolder, fileName);
            writeSucc = writeFile(context, file, buffer);
        }
        return writeSucc;
    }


    public synchronized static boolean writeFile(Context context,
                                                 String folderName, String fileName, InputStream inputStream, int storePlace) {
        boolean writeSucc = false;
        String absoluteFolder = "";

        if (STORE_PLACE_PHONE == storePlace) {
            absoluteFolder = context.getFilesDir() + File.separator
                    + folderName + File.separator;
        } else {
            boolean sdCardExist = Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED);

            if (sdCardExist) {
                absoluteFolder = Environment.getExternalStorageDirectory()
                        + File.separator + folderName + File.separator;
            } else {
                absoluteFolder = "";
            }
        }
        Loger.i("AAA", "AAA--getui--absoluteFolder:" + absoluteFolder);
        if (!StringUtils.isBlank(absoluteFolder)) {
            File fileDir = new File(absoluteFolder);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            File file = new File(absoluteFolder, fileName);
            FileOutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int readLength;
                while ((readLength = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, readLength);
                }

                outputStream.flush();

                writeSucc = true;
            } catch (Exception var15) {
                writeSucc = false;
                var15.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                        outputStream = null;
                    } catch (IOException var14) {
                        var14.printStackTrace();
                    }
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
        return writeSucc;
    }


    /**
     * 写文件
     *
     * @param context
     * @param file
     * @param buffer
     * @return
     */

    public static boolean writeFile(Context context, File file, byte[] buffer) {
        boolean writeSucc = false;
        Loger.i(TAG, "filepath--->" + file.getAbsolutePath());
        FileOutputStream out = null;
        try {
            File fileDir = file.getParentFile();
            if (fileDir != null && !fileDir.exists()) {
                fileDir.mkdirs();
            }

            // add huazhang
            if (!file.exists()) {
                file.createNewFile();
            }
            out = new FileOutputStream(file);
            out.write(buffer);
            writeSucc = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return writeSucc;
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName
     * @return
     */
    public static String getFileFormat(String fileName) {
        if (StringUtils.isBlank(fileName))
            return "";

        int point = fileName.lastIndexOf('.');
        return fileName.substring(point + 1);
    }

    /**
     * 获取文件大小
     *
     * @param size 字节
     * @return
     */
    public static String getFileSize(long size) {
        if (size <= 0)
            return "0KB";
        java.text.DecimalFormat df = new java.text.DecimalFormat("##.##");
        float temp = (float) size / 1024;
        if (temp >= 1024) {
            return df.format(temp / 1024) + "MB";
        } else {
            return df.format(temp) + "KB";
        }
    }

    /**
     * InputStream转byte数组
     *
     * @param in
     * @return
     */
    public static byte[] toBytes(InputStream in) throws IOException {
        if (in == null) {
            return null;
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int ch = 0;
        while ((ch = in.read()) != -1) {
            out.write(ch);
        }

        byte[] buffer = out.toByteArray();
        out.close();
        return buffer;
    }

    /**
     * 文件删除 如果是目录则删除目录下所有文件
     */
    public static void deleteFiles(File file) {
        // 文件
        if (file.exists() && !file.isDirectory()) {
            file.delete();
        }
        // 目录
        else {
            File[] delFiles = file.listFiles();
            int fileCounter = delFiles.length;
            for (int i = 0; i < fileCounter; i++) {
                if (delFiles[i].isDirectory()) {
                    File member = new File(delFiles[i].getAbsolutePath());
                    deleteFiles(member);
                }

                delFiles[i].delete();
            }
        }
    }

    public static void getFileSize(File file) {
        // 文件
        if (file.exists() && !file.isDirectory()) {
            size += file.length();
        }
        // 目录
        else {
            File[] delFiles = file.listFiles();
            int fileCounter = delFiles.length;
            for (int i = 0; i < fileCounter; i++) {
                if (delFiles[i].isDirectory()) {
                    File member = new File(delFiles[i].getAbsolutePath());
                    getFileSize(member);
                }

                size += delFiles[i].length();
            }
        }
    }

    /**
     * 数据流转换为字符串
     *
     * @param in
     * @return
     */
    public static String inputStreamToString(InputStream in) {
        String strInputStream = null;
        if (in != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            try {
                int i = 0;
                while ((i = in.read()) != -1) {
                    out.write(i);
                }
                out.flush();
                strInputStream = out.toString();
            } catch (IOException e) {
                e.printStackTrace();
                strInputStream = null;
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return strInputStream;
    }

    public static long getFilesAndFolderSize(File file) {
        long size = 0;
        if (file != null && file.isDirectory()) {
            File[] f = file.listFiles();
            if (f != null) {
                for (int i = 0; i < f.length; i++) {
                    File fileMsg = f[i];
                    String name = fileMsg.getName();
                    if (fileMsg.getName().equals("localClientTemplate")) {
                        continue;
                    } else {
                        if (fileMsg != null && fileMsg.isDirectory()) {
                            // 二级栏目下的问价及文件夹
                            File[] fileSecond = fileMsg.listFiles();
                            for (int j = 0; j < fileSecond.length; j++) {
                                File fileThree = fileSecond[j];
                                size += fileThree.length();
                            }
                        } else {
                            // 一级栏目下的文件
                            size += fileMsg.length();
                        }
                    }
                }
            }
        }
        return size;
    }
    // /////////////////////////////////////////////////////////

    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    /**
     * 删除单个文件
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }


    // 复制文件
    public static void copyFile(InputStream in, File targetFile)
            throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(in);

            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            // 缓冲数组
            byte[] b = new byte[BUFF_SIZE];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        } finally {
            // 关闭流
            if (inBuff != null) {
                try {
                    inBuff.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (outBuff != null) {
                try {
                    outBuff.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static boolean copyFile(String srcFileName, String destFileName,
                                   boolean overlay) {

        Loger.e("copyFile", "srcFileName: " + srcFileName + "\n"
                + "destFileName: " + destFileName + "\n"
                + overlay);

        File srcFile = new File(srcFileName);

        // 判断源文件是否存在
        if (!srcFile.exists()) {
            return false;
        } else if (!srcFile.isFile()) {
            return false;
        }
        try {
            boolean isDelete = new File(destFileName).delete();
            Loger.e("copyFile: ", "" + isDelete);
        } catch (Exception e) {

        }

        // 判断目标文件是否存在
        File destFile = new File(destFileName);
        if (destFile.exists()) {
            // 如果目标文件存在并允许覆盖
            if (overlay) {
                // 删除已经存在的目标文件，无论目标文件是目录还是单个文件
                new File(destFileName).delete();
            }
        } else {
            // 如果目标文件所在目录不存在，则创建目录
            if (!destFile.getParentFile().exists()) {
                // 目标文件所在目录不存在
                if (!destFile.getParentFile().mkdirs()) {
                    // 复制文件失败：创建目标文件所在目录失败
                    return false;
                }
            }
        }

        // 复制文件
        int byteread = 0; // 读取的字节数
        InputStream in = null;
        OutputStream out = null;

        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];

            while ((byteread = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteread);
            }
            out.flush();
            return true;
        } catch (FileNotFoundException e) {
            return false;
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String readJS(File file) {
        InputStreamReader inputReader = null;
        BufferedReader bufferReader = null;
        StringBuffer strBuffer = null;
        try {
            InputStream inputStream = new FileInputStream(file);
            inputReader = new InputStreamReader(inputStream);
            bufferReader = new BufferedReader(inputReader);
            // 读取一行
            String line = null;
            strBuffer = new StringBuffer();

            while ((line = bufferReader.readLine()) != null) {
                strBuffer.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strBuffer != null ? strBuffer.toString() : null;
    }

    public static boolean ExistSDCard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    public static boolean mkDirsNomedia(){
        String absoluteFolder;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);

        if (sdCardExist) {
            absoluteFolder = Environment.getExternalStorageDirectory()
//                    + File.separator + "Founder"
                    + File.separator + ReaderApplication.getInstace().getResources().getString(R.string.app_name)
                    + File.separator
                    + "images"
                    + File.separator;
        } else {
            absoluteFolder = "";
        }
        absoluteFolder += ".nomedia";
        File fileDirectory = new File(absoluteFolder);// 将要保存图片的路径

        if (!fileDirectory.exists()) {
            return fileDirectory.mkdirs();
        }else {
            return true;
        }
    }

}
